package com.szu.smart_illustrator.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.szu.smart_illustrator.common.R;
import com.szu.smart_illustrator.dto.param.passage.*;
import com.szu.smart_illustrator.entity.Passage;
import com.szu.smart_illustrator.mapper.PassageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.Timestamp;
import java.util.List;

@Service
public class PassageService {

    @Autowired
    PassageMapper passageMapper;

    public R<String> deletePassage( DeletePassageParamDto dto){
        passageMapper.deleteById(dto.getPassageId());
        return R.success(null);
    }

    public R<Passage> getPassageById( GetPassageByIdParamDto dto){
        return R.success(passageMapper.selectById(dto.getId()));
    }

    public R<String> savePassage(@RequestBody SavePassageParamDto dto){
          passageMapper.update(null,new UpdateWrapper<Passage>().lambda()
                  .eq(Passage::getId,dto.getPassageId())
                  .set(Passage::getContent,dto.getContent())
                  .set(Passage::getTitle,dto.getTitle())
                          .set(Passage::getPictures,dto.getPictures())
                  .set(Passage::getLastEditedDate,new Timestamp(System.currentTimeMillis()))
          );
          return  R.success(null);
    }

    public R<Passage> addPassage(@RequestBody AddPassageParamDto dto){
        Passage passage = Passage.builder()
                .title(dto.getTitle())
                .content(dto.getContent())
                .userId(dto.getUserId())
                .lastEditedDate(new Timestamp(System.currentTimeMillis()))
                .build();

        passageMapper.insert(passage);

                return  R.success(passage);


    }
    public R<List<Passage>> SearchPassages(SearchPassagesParamDto dto){
        return  R.success(passageMapper.selectList(new QueryWrapper<Passage>().lambda()
                .like(Passage::getTitle,String.format("%%%s%%",dto.getTitle()))
                .eq(Passage::getUserId,dto.getUserId())
        ));
    }
}
